<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="query.str"
        placeholder="动态标题或内容"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        style="margin-left: 10px;"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
      border
      style="width: 100%"
      fit
    >
      <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
      <el-table-column align="center" prop="id" label="ID" width="300"></el-table-column>
      <el-table-column align="center" prop="title" label="标题"></el-table-column>
      <el-table-column align="center" prop="content" label="内容"></el-table-column>
      <el-table-column align="center" prop="tag" label="标签"></el-table-column>
      <el-table-column align="center" prop="user.nickName" label="发布用户"></el-table-column>
      <el-table-column align="center" prop="receive_order.user.nickName" label="接收用户"></el-table-column>
      <el-table-column align="center" prop="status" label="状态"></el-table-column>
      <el-table-column align="center" prop="is" label="类型"></el-table-column>
      <el-table-column align="center" prop="price" label="价格"></el-table-column>

      <el-table-column align="center" label="操作" width="200px">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate($index)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>10"
      :total="total"
      :page.sync="query.page"
      :limit.sync="query.count"
      @pagination="fetchData"
    />

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="right" label-width="70px">
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="title!=='添加订单'" label="ID">
              <el-input v-model="temp.id" :disabled="true" />
            </el-form-item>
            <el-form-item label="标题" prop="title">
              <el-input v-model="temp.title" />
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <el-input type="textarea" :rows="5" v-model="temp.content" />
            </el-form-item>

            <el-form-item label="选择图片" v-if="title==='添加订单'">
              <el-upload
                class="upload-demo"
                ref="upload"
                action="no"
                :multiple="true"
                :file-list="fileList"
                :auto-upload="false"
                :http-request="uploadImg"
                :limit="9"
              >
                <el-button slot="trigger" size="small" type="primary">添加图片</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="订单类型">
              <el-select v-model="temp.is" placeholder="选择类型">
                <el-option
                  v-for="item in isOptions"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="padding-left:20px;">
            <el-form-item label="状态">
              <el-select v-model="temp.status" placeholder="选择状态">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="标签">
              <el-input v-model="temp.tag" />
            </el-form-item>
            <el-form-item label="价格">
              <el-input v-model="temp.price" />
            </el-form-item>
            <el-form-item label="发布用户">
              <el-select v-model="temp.userId" placeholder="选择用户">
                <el-option
                  class="user-option"
                  v-for="item in userOptions"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                >
                  <div class="user-option-item">
                    <el-image class="user-img" :src="baseUrl + item.avatar" />
                    <div>{{item.label}}</div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="title==='添加订单'?createData():updateData()">完成</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList, deleteOrder, updateOrder, addOrder } from "@/api/order";
import axios from "axios";
import { getUserList } from "@/api/userset";
import Pagination from "@/components/Pagination";
export default {
  name: "user",
  components: { Pagination },
  data() {
    return {
      baseUrl: this.$store.state.app.baseUrl,
      title: "添加订单",
      listLoading: true,
      list: [],
      total: 0,
      dialogFormVisible: false,
      query: {
        page: 1,
        count: 20,
        str: undefined,
      },
      uploadData: {
        userId: "1",
        orderId: "1",
      },
      fileList: [],
      //用户选项
      userOptions: [],
      statusOptions: [
        { value: 0, label: "发布订单" },
        { value: 1, label: "已接收" },
        { value: 2, label: "已完成" },
      ],
      isOptions: [
        { value: 0, label: "发布" },
        { value: 1, label: "接收" },
      ],
      search: "",
      temp: {},
    };
  },
  created() {
    this.fetchData();
    this.getUser();
  },

  methods: {
    async fetchData() {
      this.listLoading = true;
      await getOrderList(this.query).then((res) => {
        this.list = res.data.list;
        this.total = res.data.total;
        console.log(res.data);
      });
      this.listLoading = false;
    },

    //获取用户
    async getUser() {
      await getUserList().then((res) => {
        res.data.list.forEach((element) => {
          this.userOptions.push({
            value: element.id,
            label: element.nickName,
            avatar: element.avatar,
          });
        });
        console.log(this.userOptions);
      });
    },

    handleUpdate(index) {
      // this.resetTemp();
      this.dialogFormVisible = true;
      this.title = "修改用户订单";
      this.temp = this.list[index];
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    handleFilter() {
      this.query.page = 1;
      this.fetchData();
      console.log(
        this.list.filter(
          (data) =>
            !this.search ||
            data.name.toLowerCase().includes(this.search.toLowerCase())
        )
      );
    },

    handleCreate() {
      this.title = "添加订单";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    uploadImg(val) {
      let fd = new FormData();
      fd.append("userId", this.uploadData.userId);
      fd.append("orderId", this.uploadData.orderId);
      fd.append("file", val.file);
      axios.post(this.baseUrl + "/api/upload", fd).then((res) => {
        console.log(res);
      });
    },
    handleDelete(row) {
      this.$confirm(`你确定要删除订单${row.title}吗`, "删除订单?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteOrder(row.id).then((res) => {
          this.showMsg(res.code, "删除成功");
          this.fetchData();
        });
      });
    },
    //添加
    createData() {
      addOrder(this.temp).then((res) => {
        this.uploadData = {
          userId: res.data.userId,
          orderId: res.data.id,
        };
        this.$refs.upload.submit();
        this.showMsg(res.code, "添加成功");
        this.dialogFormVisible = false;
        this.fetchData();

        this.temp = {};
        this.fileList = [];
      });
    },
    //修改
    updateData() {
      let body = {
        title: this.temp.title,
        status: this.temp.status,
        tag: this.temp.tag,
        content: this.temp.content,
        userId: this.temp.userId,
        is: this.temp.is,
        price: this.temp.price,
      };
      updateOrder(this.temp.id, body).then((res) => {
        this.showMsg(res.code, "修改成功");
        this.dialogFormVisible = false;
        this.fetchData();
      });
    },

    showMsg(code, msg) {
      if (code == 200) {
        this.$message({
          message: msg,
          type: "success",
        });
      } else {
        this.$message({
          message: "出错了！！！！！！！！！！",
          type: "warning",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.user-option {
  height: 60px;
  padding: 10px;
  .user-option-item {
    display: flex;
    align-items: center;
  }
  .user-img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
  }
}
</style>
